import os
import sys
import argparse
from services.recommendation_service import RecommendationService
import time
from utils.db import get_mysql_conn, get_redis_conn, close_all_connections
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime

def check_database_connections():
    """检查数据库连接"""
    print("正在检查数据库连接...")
    
    # 清除所有旧连接
    close_all_connections()
    
    # 检查MySQL连接
    mysql_conn = get_mysql_conn(max_retries=3, force_new=True)
    if not mysql_conn:
        print("错误: 无法连接到MySQL数据库，请检查配置和网络")
        return False
    
    # 检查Redis连接
    redis_conn = get_redis_conn(max_retries=3, force_new=True)
    if not redis_conn:
        print("错误: 无法连接到Redis服务器，请检查配置和网络")
        return False
    
    print("数据库连接正常")
    return True

def main():
    parser = argparse.ArgumentParser(description='运行推荐系统服务')
    parser.add_argument('--port', type=int, default=5001, help='服务端口')
    parser.add_argument('--host', type=str, default='0.0.0.0', help='服务地址')
    parser.add_argument('--no-check', action='store_true', help='跳过数据库连接检查')
    args = parser.parse_args()
    
    # 检查数据库连接
    if not args.no_check and not check_database_connections():
        print("无法启动服务：数据库连接失败")
        sys.exit(1)
    
    # 创建推荐服务实例
    service = None
    max_retries = 5
    retry_count = 0
    
    while retry_count < max_retries:
        try:
            print(f"启动推荐服务 (尝试 {retry_count+1}/{max_retries})...")
            service = RecommendationService()
            break
        except Exception as e:
            retry_count += 1
            print(f"启动失败: {e}")
            
            # 每次重试前关闭所有数据库连接
            close_all_connections()
            
            if retry_count < max_retries:
                print(f"将在5秒后重试...")
                time.sleep(5)
            else:
                print("已达到最大重试次数，无法启动服务")
                sys.exit(1)
    
    # 启动服务
    service.start(host=args.host, port=args.port)

def start_scheduler():
    """启动定时任务"""
    scheduler = BackgroundScheduler()
    
    # 每小时更新课程热度
    scheduler.add_job(
        update_course_popularity,
        'interval',
        hours=1,
        id='update_popularity'
    )
    
    # 每6小时更新所有模型
    scheduler.add_job(
        update_all_models,
        'interval',
        hours=6,
        id='update_models'
    )
    
    # 每30分钟检查数据库连接
    scheduler.add_job(
        check_database_connections,
        'interval',
        minutes=30,
        id='check_connections'
    )
    
    scheduler.start()
    print("[%s] 开始运行定时更新任务" % datetime.now())
    print("[%s] 定时更新任务已启动" % datetime.now())
    
    return scheduler

if __name__ == "__main__":
    main() 